import 'dart:typed_data';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:pdf/pdf.dart';
import 'package:printing/printing.dart';
import 'dart:async';

import 'package:pdf/widgets.dart' as pw;
import 'package:smart_freezer/core/utils/logs.dart';

getArr(List<String> xList,
    List<double> y1List,
    List<double> y2List,) {
  var list = [];
  for (var value in xList) {
    final index = xList.indexOf(value);
    list.add([value, y1List[index], y2List[index]]);
  }
  return list;
}

getNumArr(List<String> xList) {
  List<int> list = [];
  for (var value in xList) {
    final index = xList.indexOf(value);
    list.add(index);
  }
  return list;
}

FutureOr<Uint8List> buildPdf(
    PdfPageFormat format,
    String typeName,
    List<String> xList,
    List<double> y1List,
    List<double> y2List, ) async {
  const tableHeaders = ['Time', 'T1', 'T2'];

  final dataTable = getArr(xList, y1List, y2List);
  /*
  [
    ['ROA', 30, 30],
    ['Asset Turnover', 20, 40],
    ['Leverage Ratio', 80, 12],
    ['Liquidity Ratio', 20, 60],
    ['Current Ratio', 19, 70],
    ['Quick Ratio', 34, 28],
  ]
   */

  const baseColor = PdfColors.cyan;

  // Create a PDF document.
  final document = pw.Document();

  final theme = pw.ThemeData.withFont(
    base: await PdfGoogleFonts.openSansRegular(),
    bold: await PdfGoogleFonts.openSansBold(),
  );

  // Left curved line chart
  final chart2 = pw.Chart(
    title: pw.Text('Temperature - ${typeName}'),  // 温度记录 -
    bottom: pw.ChartLegend(direction: pw.Axis.horizontal),
    grid: pw.CartesianGrid(
      xAxis: pw.FixedAxis(
          getNumArr(xList),
          textStyle: pw.TextStyle(fontSize: 10),
        format: (index) {
            if(index == 0){  // 这里只展示三个数据
              return xList[index.toInt()];
            }else if(index == xList.length - 1){
              return xList[index.toInt()];
            }else if(index == (xList.length / 2).floorToDouble()){
              return xList[index.toInt()];
            }
            return "";
        },
      ),
      yAxis: pw.FixedAxis(
        [-30, -20, -10, 0, 10, 20, 30],
        textStyle: pw.TextStyle(fontSize: 10),
        divisions: true,
      ),
    ),
    datasets: [
      pw.LineDataSet(
        legend: 'T1',
        drawSurface: true,
        isCurved: true,
        drawPoints: false,
        color: PdfColor(255 / 255.0, 35 / 255.0, 102 / 255.0, 1),
        data: List<pw.PointChartValue>.generate(
          dataTable.length,
              (i) {
            final v = dataTable[i][1] as num;
            return pw.PointChartValue(i.toDouble(), v.toDouble());
          },
        ),
      ),
      pw.LineDataSet(
        legend: 'T2',
        drawSurface: true,
        isCurved: true,
        drawPoints: false,
        color: PdfColor(87 / 255.0, 175 / 255.0, 187 / 255.0, 1),
        data: List<pw.PointChartValue>.generate(
          dataTable.length,
              (i) {
            final v = dataTable[i][2] as num;
            return pw.PointChartValue(i.toDouble(), v.toDouble());
          },
        ),
      ),
    ],
  );

  // Data table
  final table = pw.Table.fromTextArray(
    border: null,
    headers: tableHeaders,
    data: List<List<dynamic>>.generate(
      dataTable.length,
          (index) => <dynamic>[
        dataTable[index][0],
        dataTable[index][1],
        dataTable[index][2],
      ],
    ),
    headerStyle: pw.TextStyle(
      color: PdfColors.white,
      fontWeight: pw.FontWeight.bold,
    ),
    headerDecoration: const pw.BoxDecoration(
      color: baseColor,
    ),
    rowDecoration: const pw.BoxDecoration(
      border: pw.Border(
        bottom: pw.BorderSide(
          color: baseColor,
          width: .5,
        ),
      ),
    ),
    cellAlignment: pw.Alignment.center,
    cellAlignments: {0: pw.Alignment.center},
  );

  // Add page to the PDF
  document.addPage(
    pw.Page(
      pageFormat: format,
      theme: theme,
      build: (context) {
        // Page layout
        return pw.Column(
          children: [
            // 标题
            pw.Text('Williams Temperature Report',
                style: pw.TextStyle(
                  color: baseColor,
                  fontSize: 40,
                )),
            pw.Divider(thickness: 4),
            pw.Row(crossAxisAlignment: pw.CrossAxisAlignment.start, children: [
              pw.Expanded(
                  flex: 7,
                  child: pw.Column(children: [
                    pw.ConstrainedBox(
                        constraints: pw.BoxConstraints(maxHeight: 300),
                        child: chart2),

                    pw.SizedBox(height: 10),
                    // table,
                  ])),
              pw.SizedBox(width: 10),
            ]),
            // pw.Divider(),
            // 波形图
            pw.SizedBox(height: 10),
          ],
        );
      },
    ),
  );

  document.addPage(
      pw.MultiPage(
        pageFormat: format,
        theme: theme,
        build: (context) {
          return [table];
        }
      )
  );


  // Return the PDF file content
  return document.save();
}
